package com.yufei.infoExtractor.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;




/**
 * @author zhaoyufei
 * 
 *         zhao-0244@qq.com
 */
public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * ������������list��װ���ض���bean�������ؽ�� ����Ҫ��
	 */
	public static List<List> listToBeans(List<List<String>> source,
			List<String> beans, List<String> fieldOrders, String excelPath) {
		List<String> rowValues = null;
		String beanName = null;
		Object obj = null;
		List<String> columns = null;
		List<List> list = new ArrayList();
		List<Object> objList = null;
		Object[] objs = null;
		for (int i = 0; i < source.size(); i++) {
			objList = new ArrayList();
			// per row
			rowValues = source.get(i);
			objs = new Object[beans.size()];
			// per column
			for (int q = 0; q < beans.size(); q++) {
				beanName = beans.get(q);

				try {
					objs[q] = Class.forName(beanName).newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			for (int j = 0; j < rowValues.size(); j++) {

				// ������ֵ������Ķ���
				for (int q = 0; q < beans.size(); q++) {

					// �жϸ�������ж�Ӧ����
					try {
						BeanUtils.setProperty(objs[q], fieldOrders.get(j),
								rowValues.get(j));
						// PropertyUtils.setProperty(objs[q],
						// fieldOrders.get(j), rowValues.get(j));
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						continue;
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						continue;
					}

				}
			}
			for (Object obj1 : objs) {
				objList.add(obj1);
			}
			list.add(objList);
		}
		return list;

	}

	public static List<List<String>> parseExcelFile(String filePath)
			throws Exception {
		Workbook wb = null;
		wb = Workbook.getWorkbook(new FileInputStream(filePath));
		// ��õ�һ�����������
		Sheet sheet = wb.getSheet(0);
		// ��ù���������������
		int rows = sheet.getRows();
		int cols = sheet.getColumns();
		String content = null;
		// String[] rowValue=null;
		List<String> rowValue = null;
		List rowValueList = new ArrayList();
		for (int rowNumber = 1; rowNumber < rows + 1; rowNumber++) {
			rowValue = new ArrayList<String>();
			Cell[] rowCells = sheet.getRow(rowNumber - 1);
			for (int cellNumber = 1; cellNumber < cols + 1; cellNumber++) {
				content = rowCells[cellNumber - 1].getContents();


				rowValue.add(content);
				// rowValue[cellNumber-1]=rowCells[cellNumber-1].getContents();
			}
			rowValueList.add(rowValue);
		}

		return rowValueList;
	}

	/**
	 * @param <T>
	 * @param source
	 * @param fieldOder
	 *            :Ҫ��ʾ���ֶ��Լ�����
	 * @throws Exception
	 */
	public static <T> String gernerateExcelFromList(List<T> source,
			List<String> fieldOder, String savePath,List<String> headers) throws Exception {
		if(!new File(savePath).exists()){
			new File(savePath).mkdir();
		}
		String fileName=System.currentTimeMillis()+".xls";
		WritableWorkbook workbook = Workbook.createWorkbook(new File(savePath+fileName));
		WritableSheet sheet = workbook.createSheet("sheet", 0);
		Label label = null;
		String[] strs = new String[fieldOder.size()];;
		int rowNumber = 0, columnNumber = 0;
		//���ñ�ͷ
		for (int j = 0; j < strs.length; j++) {

			// column,row
			label = new Label(columnNumber, rowNumber, headers.get(j));
			sheet.addCell(label);
			columnNumber++;
		}
	    rowNumber++;
	    
	    
		for (T t : source) {
			columnNumber = 0;
			// per row
			
			for (int i = 0; i < fieldOder.size(); i++) {
				strs[i] = (String) BeanUtils.getProperty(t,
						fieldOder.get(i));
			}
			for (int j = 0; j < strs.length; j++) {

				// column,row
				label = new Label(columnNumber, rowNumber, strs[j]);
				sheet.addCell(label);
				columnNumber++;
			}
			rowNumber++;
		}

		workbook.write();
		workbook.close();
		return fileName;

	}
   /* public  static void generatePdf(){
    	Document document=new Document();
    	try {
    		PdfWriter.getInstance(document, new FileOutputStream("E://temp.pdf"));
    		document.open();
    		document.add(new Paragraph("Hello Wrold"));
    		document.close();
    	} catch (Exception e) {
    		// TODO: handle exception
    	}
    }*/
	public static void main(String[] args) {
		/*
		 * try { List list= FileUtil.parseExcelFile(
		 * "D:\\work\\PalmMIS\\trunk\\WebRoot\\PalmMIS\\admin\\upload\\app\\20111011162400\\upload2\\game.xls"
		 * ); list.size(); String str=list.getClass().getName();
		 * //System.out.print(); } catch (Exception e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); } List<Item> items=new ArrayList();
		 * items.add(new Item("fdfdf","dfdfwererererererererere"));
		 * items.add(new Item("fdfdf","dfdf")); items.add(new
		 * Item("fdfdf","dfdf")); items.add(new Item("fdfdf","dfdf"));
		 * items.add(new Item("fdfdf","dfdf")); items.add(new
		 * Item("fdfdf","dfdf")); List<String> fieldOrder=new ArrayList();
		 * fieldOrder.add("name"); fieldOrder.add("sex");
		 */
		/*
		 * try { FileUtil.gernerateExcelFromList(items, fieldOrder); } catch
		 * (Exception e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */// fe01_0000.xls
		List list1 = new ArrayList();
		list1.add("com.ourpalm.mis.object.business.Service");
		list1.add("com.ourpalm.mis.object.business.ServiceDetail");
		String[] orders = { "service_id", "service_name", "service_fee_type",
				"service_fee", "service_validtime",
				"service_audit_passed_time", "service_audit_time",
				"service_status", "service_open", "cpservice_id", "", "cpid",
				"spid", "billing_A", "billing_B", "compony_id",
				"service_description" };
		List fieldOrder = new ArrayList();
		for (String str : orders) {
			fieldOrder.add(str);
		}
		try {
			List list = FileUtil.parseExcelFile("D:\\Book1.xls");
			FileUtil.listToBeans(list, list1, fieldOrder, null);
			// System.out.print();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
